package com.jsy.mini12306.ticketsales.bo;

import com.jsy.mini12306.common.entity.SeatType;
import com.jsy.mini12306.common.entity.Train;
import com.jsy.mini12306.common.entity.TrainPassStation;
import com.jsy.mini12306.common.entity.TrainStationSeatStatus;
import com.jsy.mini12306.ticketsales.entity.*;
import com.jsy.mini12306.ticketsales.vo.DrivingPlanVO;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.time.Duration;
import java.time.LocalDate;
import java.util.*;

/**
 * @author: SongyangJi
 * @description:
 * @since: 2021/9/2
 */


@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
public class DrivingPlan {
    /**
     * 列车
     */
    Train train;
    /**
     * 出发车站
     */
    TrainPassStation departStation;
    /**
     * 到达车站
     */
    TrainPassStation arrivalStation;
    /**
     * 出行日期
     */
    LocalDate workingDate;

    Map<SeatType, Integer> seatNums;

    Map<SeatType, Float> seatPrices;


    public List<TrainStationSeatStatus> getSeatStatusOfPassStations(SeatType seatType) {
        ArrayList<TrainStationSeatStatus> res = new ArrayList<>();
        /*
         * 排序 （可能是冗余操作）
         */
        train.getTrainPassStations().sort(Comparator.comparingInt(TrainPassStation::getSequence));
        train.getTrainPassStations().stream().filter(trainPassStation -> {
            int sequence = trainPassStation.getSequence();
            // 终点站就下车了，所以是 <
            return sequence >= departStation.getSequence() && sequence < arrivalStation.getSequence();
        }).forEach(trainPassStation -> res.add(TrainStationSeatStatus.builder().
                trainId(train.getTrainId()).stationId(trainPassStation.getStationId()).type(seatType).build()));
        return res;
    }


    public DrivingPlanVO getVO() {
        int gap = (int) Duration.between(departStation.getDepartTime(), arrivalStation.getArrivalTime()).toMinutes();
        if (gap < 0) {
            gap += 24 * 60;
        }
        if (seatNums == null) {
            seatNums = new HashMap<>();
            seatNums.put(SeatType.BUSINESS,null);
            seatNums.put(SeatType.FIRST,null);
            seatNums.put(SeatType.SECOND,null);
        }
        if (seatPrices == null) {
            seatPrices = new HashMap<>();
            seatPrices.put(SeatType.BUSINESS,null);
            seatPrices.put(SeatType.FIRST,null);
            seatPrices.put(SeatType.SECOND,null);
        }
        return new DrivingPlanVO(train, departStation, arrivalStation, seatNums, seatPrices, gap);
    }

}
